"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 备升主时，主节点网卡down
Create At   : 2021/07/30
@zou_jialiang0505328126
Description :
    1.停止主节点
    2.备升主
    3.切换的同时注入网卡down
    4.执行事务
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
    Modified by @li-xin12345 2022/10/10: 配置tpcc用户白名单
"""

import unittest
import time
import os
from yat.test import Node
from yat.test import macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class NetWork(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_root_node = Node(node='PrimaryRoot')
        self.sta1_root_node = Node(node='Standby1Root')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.sta1_user_node = Node(node='Standby1DbUser')
        self.com = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta1_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.flg = True

        self.hostmsg = self.primary_root_node.sh('hostname;').result()
        self.log.info(f'hostname is {self.hostmsg}')

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.primary_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.primary_user_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

    def test_main(self):
        text = '----step1: 停止主节点 expect:成功----'
        self.log.info(text)
        result = self.pri_sh.stopDbInstance()
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, result,
                      '执行失败' + text)

        text2 = '----step2: 备升主 expect:成功----'
        self.log.info(text)
        failover_thread = ComThread(
            self.sta1_sh.executeGsctl, args=(
                'failover', self.constant.FAILOVER_SUCCESS_MSG,))
        failover_thread.setDaemon(True)
        failover_thread.start()

        text = '----step3: 注入网卡down故障 expect:成功---'
        self.log.info(text)
        inject_command = f"rNet_down (dev, time)" \
            f"values({self.networkcard}, 30)"
        cfe_thread = ComThread(
            self.com.cfe_inject, args=(self.primary_root_node,
                                       inject_command,))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join(40)
        result = cfe_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.cfe_inject_netdown_success_msg, result,
                      '执行失败' + text)

        self.log.info("------------获取failover结果----------------")
        failover_thread.join(180)
        result = failover_thread.get_result()
        self.log.info(result)
        self.assertTrue(result, '执行失败' + text2)

        text = '----step4: 执行TPCC expect:成功----'
        self.log.info(text)
        guc_cmd = f'source {macro.DB_ENV_PATH}; ' \
            f'gs_guc reload -D {macro.DB_INSTANCE_PATH} -h ' \
            f'"host {self.sta1_user_node.db_name} ' \
            f'{self.sta1_user_node.db_user} ' \
            f'{self.sta1_user_node.db_host}/32 sha256";'
        self.log.info(guc_cmd)
        guc_msg = self.sta1_user_node.sh(guc_cmd).result()
        self.log.info(guc_msg)
        self.assertIn("Failed instances: 0", guc_msg)
        result = self.com.startTPCC(self.sta1_root_node, macro.TPCC_PATH)
        self.log.info(result)
        self.assertIn(self.constant.TPCC_SUCCESS_MSG, result,
                      '执行失败:' + text)
        self.flg = False

    def tearDown(self):
        if self.flg:
            self.log.info("等待故障结束")
            time.sleep(30)
        self.log.info("---------------还原集群------------")
        self.pri_sh.executeGsctl(
            'start', 'start', '-M standby')
        self.pri_sh.executeGsctl(
            'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
        self.pri_sh.exec_refresh_conf()
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
